package com.vn.ltedatausagetracking.login;

import java.io.IOException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;

import com.vn.ltedatausagetracking.R;
import com.vn.ltedatausagetracking.common.Constants;
import com.vn.ltedatausagetracking.common.Utils;
import com.vn.ltedatausagetracking.dto.BaseStatusDto;
import com.vn.ltedatausagetracking.dto.Userdto;
import com.vn.ltedatausagetracking.track.activity.TrackingActivity;

public class LoginActivity extends Activity implements OnCheckedChangeListener {
	private CheckBox cbSaveUser;
	private EditText edtUserName;
	private EditText edtPassword;
	private static final String SAVE_PASSWORD_KEY = "save_pass_key";
	private static final String PASSWORD_KEY = "pass_key";
	private static final String USER_NAME_KEY = "username_key";
	private LoginAsynTask loginAsynTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_layout);
		cbSaveUser = (CheckBox) findViewById(R.id.cb_save_user);
		cbSaveUser.setOnCheckedChangeListener(this);
		edtPassword = (EditText) findViewById(R.id.edt_password);
		edtUserName = (EditText) findViewById(R.id.edt_username);

	}

	@Override
	protected void onResume() {
		init();
		super.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		if (loginAsynTask != null) {
			loginAsynTask.dismissDialog();
			loginAsynTask.cancel(true);
			loginAsynTask = null;
		}
		super.onPause();
	}

	private void init() {
		boolean isChecked = Utils.getBoolean(this, SAVE_PASSWORD_KEY, false);
		if (!isChecked) {
			return;
		}
		cbSaveUser.setChecked(isChecked);

		String password = Utils.getString(this, PASSWORD_KEY, null);
		String username = Utils.getString(this, USER_NAME_KEY, null);
		if (username == null) {
			return;
		}
		edtUserName.setText(username);
		if (password == null) {
			return;
		}
		edtPassword.setText(password);
		if (!getIntent().getBooleanExtra("login", true)) {
			return;
		}
		loginAsynTask = new LoginAsynTask();
		loginAsynTask.execute(new Userdto(username, password));
	}

	public void onLogin(View v) {
		String sms = "";
		String username = edtUserName.getText().toString();
		String password = edtPassword.getText().toString();
		if (username.equals("")) {
			sms += "User name";
		}
		if (password.equals("")) {
			sms += " Password";
		}
		if (!sms.equals("")) { // Have empty field
			Toast.makeText(LoginActivity.this, sms + " must be filled",
					Toast.LENGTH_LONG).show();
			return;
		}
		if (cbSaveUser.isChecked()) {
			Utils.putString(LoginActivity.this, PASSWORD_KEY, edtPassword
					.getText().toString());
			Utils.putString(LoginActivity.this, USER_NAME_KEY, edtUserName
					.getText().toString());
		}
		// Send request
		loginAsynTask = new LoginAsynTask();
		loginAsynTask.execute(new Userdto(username, password));

	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		Utils.putBoolean(LoginActivity.this, SAVE_PASSWORD_KEY, isChecked);
		if (!isChecked) {
			Utils.putString(LoginActivity.this, PASSWORD_KEY, null);
			Utils.putString(LoginActivity.this, USER_NAME_KEY, null);
		}
	}

	private class LoginAsynTask extends AsyncTask<Userdto, Void, BaseStatusDto> {

		private ProgressDialog progressDialog;

		private void dismissDialog() {
			if (progressDialog != null && progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			progressDialog = new ProgressDialog(LoginActivity.this);
			progressDialog.setMessage("Loginning...");
			progressDialog.show();
			super.onPreExecute();
		}

		@Override
		protected BaseStatusDto doInBackground(Userdto... params) {
			// TODO Auto-generated method stub
			BaseStatusDto statusDto = new BaseStatusDto();
			try {
				String json = Utils.sendToServer("http://localhost:8080",
						Utils.convertUserInfoToJson(params[0]));
				statusDto = Utils.convertJsonToBaseStatusDto(json);
			} catch (IOException e) {
				e.printStackTrace();
				// return new BaseStatusDto(Constants.STATUS_OFFLINE,
				// e.toString());
				// test
				return new BaseStatusDto(Constants.STATUS_OK, e.toString());
			}
			return statusDto;
		}

		protected void onPostExecute(BaseStatusDto result) {
			dismissDialog();
			if (result.getStatus() != Constants.STATUS_OK) {
				Toast.makeText(LoginActivity.this, result.getMessage(),
						Toast.LENGTH_LONG).show();
				return;
			}
			Intent intent = new Intent(LoginActivity.this,
					TrackingActivity.class);
			startActivity(intent);
			finish();
			super.onPostExecute(result);
		};

	}
}
